/**
 *  //"block"模式
 *  uploadUtil.build({
 *		mode: "block",					
 *		blockOptions: {
 *			blockContainer: "attachlist1",
 *		},
 *		resourceId: "001"
 *	}); 
 *  //"modal"模式
 *	uploadUtil.build({
 *		mode: "modal",
 *    	resourceId: "001"
 *	}); 
 *  如果是"modal"模式，需要显示调用showModal方法来打开文件上传窗口
 *  uploadUtil.showModal("001");
 *  
 *  "modal"的另一种模式"sharedModal"，此模式下，所有的资源共享同一个文件模态窗口
 *  
 *  <!-- 其他附件列表 ${id}附件关联实体id -->
 *      <div class="tab-pane fade" id="commonAttachList">
 *  		<Iframe src='${baseURL}/common/attach/attachlist/list.do?resourceId=${id}' width="100%" scrolling="yes" frameborder="0" id="firmAttachList" onload="changeFrameHeight('firmBaseInfoProduct')"></iframe> 
 *  	</div>
 *  
 * @param upload
 * @auth lps 2017-6-8
 */
(function(upload){
	//上传附件URL
	var uploadUrl = baseURL + "/attach/action/attachsupport/uploadAttach.do?rand=" + Math.random();
	//查询附件列表URL
	var listUrl = baseURL + "/attach/action/attachsupport/listJSON.do?rand=" + Math.random();
	//下载附件URL
	var downloadUrl = baseURL + "/attach/action/attachsupport/downloadAttach.do?rand=" + Math.random();
	//删除附件URL
	var deleteUrl = baseURL + "/attach/action/attachsupport/delete.do?rand=" + Math.random();

	upload.options = {
		mode: "block",					//展示模式，"block"块级元素展示，"modal"模态窗口展示, "sharedModal"共享模态窗口
		blockOptions: {
			blockContainer: null,
		},
		modalOptions: {
			title: "附件上传",
			height: 400,
	        width: 700,
	        close: function(){}
		},					
		validFileName : false,
		validFileSize : true,
		allowUpload: false,				//是否允许上传 (国资委等管理员账号均无上传，删除的权限，所以改成false)
		allowDelete: false,				//是否允许删除
		allowDownlaod: true,			//是否允许下载
		remark:null,					//说明
		resourceId: null,				//上传附件关联的资源ID
		//是否允许其他人操作本人上传附件 如果true 则允许操作非本人上传附件 如果为false 则不允许操作非本人上传附件
		allowShare:true,
		maxSize:100,
	},
	/*
	 * 页面初始化 
	 * params 初始化参数
	 */
	upload.build = function(params) {
		var _p = new Object();
		for (var attr in params) {
			_p[attr] = params[attr];
			if (upload.options.hasOwnProperty(attr))
				upload.options[attr] = params[attr];
		}
		
		var _opt = upload.options;
		if (_opt.mode == "block")
			buildBlock(_opt.blockOptions.blockContainer, _opt.resourceId, _p,_opt.maxSize);
		else if (_opt.mode == "modal")
			buildModal(_opt.modalOptions, _opt.resourceId, false, _p);
		else if (_opt.mode == "sharedModal")
			buildModal(_opt.modalOptions, _opt.resourceId, true, _p);
	},
	/*
	 * 上传附件
	 * 参数:obj 附件 resourceId 上传附件关联的资源ID  isShared 判断是否模式是"sharedModal"文件窗口资源共享
	 */
	upload.uploadFile = function(obj, resourceId, isShared) {
		var fileElem = obj;
		resourceId = isShared ? upload.options.resourceId : resourceId;
		asyncUploadFile(fileElem, resourceId, isShared);
	},
	/*
	 * Modal模式加载modal
	 */
	upload.showModal = function(resourceId) {
		$("#file-dialog-" + resourceId).dialog("open");
		upload.options.resourceId = resourceId;
	}
	/*
	 * ShareModal模式加载modal
	 */
	upload.showSharedModal = function(resourceId,allowEdit) {
		upload.options.resourceId = resourceId;
		upload.options.allowUpload = allowEdit;				
		upload.options.allowDelete = allowEdit;	
		$("#file-dialog").dialog("open");
	}
	
	/*
	 * 删除附件
	 * 参数: row 所在列 attachId 附件Id
	 */
	upload.deleteAttach = function(row, attachId) {
		BT.showConfirm("删除","你确定删除所选附件吗？",function(){
			if(!upload.options.allowDelete){
        		BT.showWarning("权限不足，无法删除该附件！");
        	}else{
        		$.ajax({
        			url: deleteUrl,
        			data: {attachId: attachId},
        			type: "POST",
        			success: function(data){
        				if (data.hasOk) {
        					BT.showSuccess("删除附件成功");
        					$("#tb_AttachBox").bootstrapTable("refresh");
        					//$(row).parent().parent().remove();
        				}
        				else
        					BT.showError("删除附件失败");
        			},
        			error: function(XMLHttpRequest, textStatus, errorThrown) {
        				BT.showError("删除附件失败");
        			}
        		});//end ajax
        	}
		}) 
	}
	
	var css = "";
	css += "<style type=\"text/css\">";
	css += "</style>";
	/*
	 * Block模式
	 * 加载页面html元素
	 * 参数: container 页面容器Id resourceId 上传附件关联的资源ID 
	 *      isShared 判断是否模式是"sharedModal"文件窗口资源共享 params 初始化传入的参数
	 */
	function renderBlockHtml(container, resourceId, isShared, params,maxSize) {
		var id = !isShared ? "attach-list-wrapper-" + resourceId : "attach-list-wrapper";
		var attachId = !isShared ? "attach-" + resourceId : "attach"
		var blockHtml = "";
		blockHtml += "	<div id=\"" + id + "\">";
		blockHtml += "	 <div class=\"cont-table frameBorder\" >";
		blockHtml += "		<div class=\"attach_head\">";
	
		if(upload.options.allowUpload){ 
			blockHtml += "	<div class=\"upload-file\">";
			blockHtml += "	<input type=\"file\" class=\"file-select\" value=\"上传附件\" id=\"" + resourceId + "\" name=\"attach\" onchange=\"uploadUtil.uploadFile(this,'" + resourceId + "', " + isShared + ");return false;\" />";
			blockHtml += "<div class=\"top-nav\">";
			blockHtml += "		<button class=\"btn btn-normal btn-blue\">上传文件</button>";
			blockHtml += "	</div>";
			blockHtml += "	</div>";
			blockHtml += "			<span style=\"margin-left:15px\" >注：" + (params.remark || "上传的附件不能大于"+maxSize+"M") + "</span>";
		}
		blockHtml += "		</div>";
		blockHtml += "		<div class=\"table-sheet\">";
		blockHtml += "		<table id=\"tb_AttachBox\">";
		blockHtml += "		                 </table>";
		blockHtml += "	                     </div>";
		blockHtml += "	                     </div>";
		$(container).append(blockHtml);
		return id;
	}
	/*
	 * Block模式
	 * 页面初始化和加载数据
	 * 参数:blockCotainer 页面容器Id,resourceId 上传附件关联的资源ID ，params 初始化传入的参数
	 */
	function buildBlock(blockContainer, resourceId, params,maxSize) {
		//加载页面
		renderBlockHtml($("#" + blockContainer), resourceId, false, params,maxSize);
		//加载列表数据
		initTable(resourceId);
	} 
	/*
	 * modal模式
	 * 页面初始化加载数据
	 * 参数:resourceId 上传附件关联的资源ID ， isShared 判断是否模式是"sharedModal"文件窗口资源共享,params 初始化传入的参数
	 */
	function renderDialogHtml(resourceId, isShared, params) {
		var id = !isShared ? "file-dialog-" + resourceId : "file-dialog";
		var dialogHtml = "";
		dialogHtml += "<div id=\"" + id + "\">";
		dialogHtml += "</div>";
		$("body").append(dialogHtml);
		renderBlockHtml($("#" + id), resourceId, isShared, params);
		return id;
	}
	/*
	 * modal模式
	 * 初始化dialog
	 */
	function buildModal(_modalOpt, resourceId, isShared, params) {
		var dialogId = renderDialogHtml(resourceId, isShared, params);
		$("#" + dialogId).dialog({
	        autoOpen: false,
	        title: _modalOpt.title,
	        height: _modalOpt.height,
	        width: _modalOpt.width,
	        modal: true,
	        buttons: {
				"关闭": function() {
					$("#" + dialogId).dialog( "close" );
				}
			},
	        close: function() {
	        	isShared ? clearData() : clearData(upload.options.resourceId);
	        	_modalOpt.close();
	        },
			open: function() {
				loadData(upload.options.resourceId, isShared);
			}
		});
	}
	/*
	 * 加载数据 用于非bootstraptable样式加载列表页面和数据
	 * 参数:resourceId 上传附件关联的资源ID isShared 判断是否模式是"sharedModal"文件窗口资源共享,params 初始化传入的参数
	 */
	function loadData(resourceId, isShared) {
		$.ajax({
    		url: listUrl,
    		data: {resourceId: resourceId},
    		type: "POST",
    		success: function(data){
    			for (var i = 0; i < data.Rows.length; i++) {
    				isShared ? appendFile(data.Rows[i]) :
    						appendFile(data.Rows[i], resourceId);
    			}
    		},
    		error: function(XMLHttpRequest, textStatus, errorThrown) {
    			console.log("加载附件列表错误")
    		}
    	});
	}
	/*
	 * 上传附件
	 * 参数 fileElem 文件对象 ,resourceId 上传附件关联的资源ID ,isShared 判断是否模式是"sharedModal"文件窗口资源共享,
	 */
	function asyncUploadFile(fileElem, resourceId, isShared) {
		//判断是否允许上传
		if(!upload.options.allowUpload){
    		BT.showWarning("权限不足，无法新增新的附件！");
    	}else{
    		var id = $(fileElem).attr("id");
    		if(upload.options.validFileName && !validUploadFile(fileElem)) return false;
    		//上传附件
    		$.ajaxFileUpload({
    			url: uploadUrl + "&resourceId=" + resourceId,
    			secureuri: false,
    			fileElementId: id,
    			dataType:"text",
    			success:function(data, status){
    				//上传成功 刷新列表
    				if(data){
    					var jsonData = JSON.parse(data);
    					if (jsonData.error)
    						BT.showError(jsonData.error)
    						else{
    							BT.showSuccess("上传成功!");
    							var file = document.getElementById(resourceId);
    							file.outerHTML = file.outerHTML;
    							$("#tb_AttachBox").bootstrapTable("refresh");
    						/*	isShared ? appendFile(jsonData) :
    								appendFile(jsonData, resourceId);
    								*/
    								}
    				}else{
    					BT.showError("上传失败，请重新上传！");
    				}
    			},
    			//服务器响应失败
    			error:function(data,status,e){
    				BT.showError("上传失败：[" + e + "]， 请联系管理员！");
    			}
    		});
    	}
	}
	function queryParams(params){
	    return{
	        pageNo: params.pageSize,//每页多少条数据
	        perPageSize:params.pageNumber,//请求第几页
	    }
	}
	/*
	 * 加载表格
	 * 参数: resourceId 上传附件关联的资源ID
	 */
	function initTable(resourceId){
		$('#tb_AttachBox').bootstrapTable({
			url:listUrl+"&resourceId="+resourceId ,
			method: 'post',
			contentType: "application/x-www-form-urlencoded",
       		sidePagination: "server",
       		queryParams: queryParams,
       		queryParamsType:"undenfied",
            striped: true,                      //是否显示行间隔色
            pagination: true,
	        pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 15,                       //每页的记录行数（*）
            pageList: [15, 25, 50, 100],        //可供选择的每页的行数（*）
	        clickToSelect: true,                //是否启用点击选中行
            uniqueId: "id",                 //每一行的唯一标识，一般为主键列
            dataField : "Rows",
            totalField:"Total",
       		columns: [{
                   field: 'number',
                   title: '序号',
   	               formatter: function (value, row, index) {
   	                   return (index+1);  
   	               }
               }, {
                   field: 'attachName',
                   title: '名称',
                   formatter: function (value, Rows, index) {
                	   var attachId = Rows.attachId ; 
                	   var attachName = Rows.attachName
   	                   return '<a href=\"javascript:downLoad(\'' + attachId + '\')\">'+value+'</a>';
	               }
               }, {
                   field: 'attachSuffix',
                   title: '文件类型',
                   formatter: function (value, Rows, index) {
                	   value = value.replace(/\./g,"");
                	   return value+"文件";
	               }
			   }, {
                   field: 'creatorName',
                   title: '上传人'
			   }, {
                   field: 'createTimeDesc',
                   title: '上传时间',
                  
			   }, {
                   field: 'attachMSize',
                   title: '大小',
			   }, {
                   field: 'operate',
                   title: '操作',
                   formatter: function (value, Rows, index) {
	                	if(!upload.options.allowDelete){
	                   		 return '--';
	                   	}else if(!upload.options.allowShare && !Rows.self){
	                   		return '--';
	                   	}else{
	             		   return '<button class="btn-clear" onclick="uploadUtil.deleteAttach(this,\''+ Rows.attachId+'\')">删除</button>';
	                   	}
	               }
			   }]
		})
	}
	
	function appendFile(data, resourceId) {
		var trHtml = "";
		trHtml += "				<tr>"
		trHtml += "					<td>" + data.attachName + "<input type=\"hidden\" name=\"attachId\" id=\"attachId\" value=\"" + data.attachId + "\" /></td>";
		trHtml += "					<td>" + data.createTimeDesc + "</td>";
		trHtml += "					<td>" + data.creatorName + "</td>";
		trHtml += "					<td>" + data.attachMSize + "</td>";
		trHtml += "					<td>" ;
		if(upload.options.allowDelete) trHtml += "<a href=\"javascript:void(0);\" onclick=\"uploadUtil.deleteAttach(this,'" + data.attachId + "')\">删除</a>&nbsp;&nbsp;" ;
		trHtml +="<a href=\"" + buildDownloadUrl(data.attachId, data.attachName) + "\">下载</a></td>";
		trHtml += "				</tr>";
	
		var wrapper = resourceId ? $("#attach-list-wrapper-" + resourceId) 
				: $("#attach-list-wrapper");
		$(wrapper).find("tbody").append(trHtml);
	}
	//清除数据
	function clearData(resourceId) {
		var wrapper = resourceId ? $("#attach-list-wrapper-" + resourceId) 
				: $("#attach-list-wrapper");
		$(wrapper).find("tbody").html("");
	}
    /*
     * 创建附件下载URL 
     * 参数:attachId 附件ID attachName 附件名称
     */
	function buildDownloadUrl(attachId, attachName) {
		downLoad(attachId , attachName);
		attachName = encodeURI(encodeURI(attachName));
		return downloadUrl + "&attachId=" + attachId + "&attachName=" + attachName;
	}
	/*
	 * 获取文件名
	 * 参数 fileEle 文件
	 */
	function getUploadFileName(fileEle){
		var fileName = $(fileEle).val();
		var pos=fileName.lastIndexOf("\\");
		return fileName.substring(pos+1);  
	}
	function getUploadFileSize(fileEle){
		//var dom = document.getElementById($(fileEle).attr("id"));
		//alert(dom.fileSize);
		//alert(dom.files[0]);
		return 0; 
	}
	/*
	 * 校验文件名
	 */
	function validUploadFile(fileEle){
		var fname = getUploadFileName(fileEle);
		fname = fname.substring(0,fname.lastIndexOf("."));
		var reg = /[\u4E00-\u9FA5]{1,100}/g;
		if(fname.length < 4 || !reg.test(fname)){
			alert("上传文件名称至少4个汉字!");
			return false;
		}
		return true;
	}
}(window['uploadUtil'] = {}));